require "ap-util"
require "config-biz"
require "cloud-wifi-biz"
require "config-init-biz"
require "tcp-biz"
errors = ""
self = string.gsub(wifi.sta.getmac(),":","")

connectFail = false
connectFailTime = 0

reTryConnectToCloud = false


function init()
    wifi.setmode(wifi.STATION)
    wifi.sta.getap(1, connectToWifi)
end

function connectToWifi(t)
    wifi.setmode(wifi.STATION)
    __unregisterWifiEvent()
    wifi.sta.disconnect()
    local aps = getAps(t)
    if(isExistWifiConfig()) then
        local exitsConfigAp = false
        local wifiConfig = getWifiConfig()
        if(aps[wifiConfig["ssid"]]) then
            exitsConfigAp = true
        end
        if(exitsConfigAp) then 
            if(__b3_connectToCloudWifiConfig(wifiConfig) == false) then
                print("cloud wifi config connect fail:"..errors)
                __connectToInitWifiConfig()
            end
        else
            errors = errors.."don't have cloud wifi aps."
            print(errors)
            __connectToInitWifiConfig(t)
        end
    else
        errors = errors.."dont have cloud config wifi params."
        print(errors)
        __connectToInitWifiConfig(t)
    end
end

--------------------------------------init wifi connect---------------------------------------------------
function __connectToInitWifiConfig(t) 
    local configs = getInitConfig()
    local wifiConfig = configs["wifi"]
    connectFailTime = 0
    __unregisterWifiEvent()
    __registerWifiEvent(__init_wifi_success, __init_wifi_fail)
    print("connecting to init wifi: ssid="..wifiConfig["ssid"].." password="..wifiConfig["password"])
    
    wifi.setmode(wifi.STATION)
    wifi.sta.config(wifiConfig["ssid"], wifiConfig["password"])
end

function __init_wifi_fail(t)
    print("__init_wifi_fail:todo")
    connectFailTime = connectFailTime + 1
    if(connectFailTime > 10 or reTryConnectToCloud) then
        --connectFail = true
        wifi.sta.getap(1, connectToWifi)
    end
end

function __registerWifiEvent(sucess, fail)
    wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, fail)
    wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, sucess)
end

--- afe
function __unregisterWifiEvent()
    wifi.eventmon.unregister(wifi.eventmon.STA_DISCONNECTED)
    wifi.eventmon.unregister(wifi.eventmon.STA_GOT_IP)
end

init()
